import {defineStore} from "pinia";
import {reqVerificationCdoe,reqUserLogin} from '@/api/user/user.ts'
import type {LoginData,UserLoginResponseData} from "@/api/user/type.ts";
import {UserState} from "@/store/mod/interface";
import {SET_TOKEN,GET_TOKEN,REMOVE_TOKEN} from '@/utils/user.ts'

const useUserStore  = defineStore('User',{
    state:():UserState=>{
        return {
            visiable:false, //用于控制登录组件的dialog显示与隐藏
            code:'',
            userInfo:JSON.parse(GET_TOKEN() as string)||{}
        }
    },
    actions:{
        /**
         * 获取验证码
         * @param phone  必须现有手机号
         */
        getCode(phone:string){
            reqVerificationCdoe(phone).then(result=>{
                console.log(result)
                if(result.code==200){
                    this.code=result.data
                    return 'ok'
                }
            }).catch(err=>{
                return err.mesage
            })
        },
        /**
         * 登录的功能
         */
        async userLogin(data:LoginData){
            let result:UserLoginResponseData = await reqUserLogin(data)
            this.userInfo=result.data
            // 本地存储持久化存储用户信息
            SET_TOKEN(JSON.stringify(this.userInfo))
            // console.log(this.userInfo)
        },
        loginOut(){
            REMOVE_TOKEN()
            this.userInfo={name:'',token:''}
        },
         //查询微信扫码的接口（看本地存储是否存储数据）
        queryState(){
            let id = setInterval(()=>{
                console.log('定时器')
                if(GET_TOKEN()){
                    this.visiable=false
                    this.userInfo=JSON.parse(GET_TOKEN() as string)
                    clearInterval(id)
                }
            },500)
        }
    },
    getters:{
    }
})
export default useUserStore